class TaskController < ApplicationController

  respond_to :html, :xml, :js

  def edit
    @task=Tasks.find(params[:id])
  end

  def list
    @new = Tasks.new(params[:tasks])
    @user_id=Users.find(session[:id]).id
    @list = Tasks.find_all_by_user_id(@user_id)
    @tasks= Tasks.find(:all)
  end

  def new
    @task=Tasks.new
    @user_id=Users.find(session[:id]).id
  end

  def show
    @user_id=Users.find(session[:id]).id
    @task=Tasks.find(params[:id])
    @state=@task.state.description    
    #@duration=Time.at(@task.duration).gmtime.strftime('%Rh:%Sm')
    @duration=timecalculator(@task.duration)

   
  end

  def create
    @task = Tasks.new(params[:new])
    
    if @task.save
      redirect_to :action => 'list'
      flash[:message] = 'Task successfully created'
    else
      render :action => 'new'
    end
  end

  def update
    @task = Tasks.find(params[:id])
    if @task.update_attributes(params[:task])

      redirect_to :action => 'list', :id => @task
    else
      render :action => 'list'
    end
  end

  def delete
    Tasks.find(params[:id]).destroy
    redirect_to :action => 'list'
  end

  def pause_save
    @task=Tasks.find(params[:id])
    @str=params[:stwa]
    @time1=timetosecconds(@str)
    @time2=@task.duration.to_i
    @time=@time1+@time2
    respond_to do |format|
      if @task.update_attribute("duration",@time)
        format.html
        format.js
      end
    end
  end
   
    
  

  
  ##############################Time######################################
  def timecalculator(total_seconds)
    total_seconds = total_seconds.to_i

    days = total_seconds / 86400
    hours = (total_seconds / 3600) - (days * 24)
    minutes = (total_seconds / 60) - (hours * 60) - (days * 1440)
    seconds = total_seconds % 60

    display = ''
    display_concat = ''
    if days > 0
      display = display + display_concat + "#{days}d"
      display_concat = ' '
    end
    if hours > 0 || display.length > 0
      display = display + display_concat + "#{hours}h"
      display_concat = ' '
    end
    if minutes > 0 || display.length > 0
      display = display + display_concat + "#{minutes}m"
      display_concat = ' '
    end
    display = display + display_concat + "#{seconds}s"
    display
  
  end

  def timetosecconds(time)
    temp = time.split(':')
    h2s=temp[0].to_i*3600
    m2s=temp[1].to_i*60
    s=temp[2].to_i+m2s+h2s
    return s
  end


  ###########################################################################

end
